package com.ruoyi.bantong.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

import com.ruoyi.bantong.constant.BanTongConstants;
import com.ruoyi.bantong.domain.BtOrganization;
import com.ruoyi.bantong.domain.BtUserAccountRecord;
import com.ruoyi.bantong.domain.BtUserLevel;
import com.ruoyi.bantong.domain.BtUserTicket;
import com.ruoyi.bantong.mapper.*;
import com.ruoyi.bantong.service.IBtOrganizationRechargeRecordService;
import com.ruoyi.bantong.service.IBtUserAccountRecordService;
import com.ruoyi.common.core.domain.entity.BtUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import com.ruoyi.bantong.domain.BtUser;
import com.ruoyi.bantong.service.IBtUserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户Service业务层处理
 * 
 * @author laohei
 * @date 2021-01-24
 */
@Service
public class BtUserServiceImpl implements IBtUserService 
{
    @Autowired
    private BtUserMapper btUserMapper;

    @Autowired
    private BtUserLevelMapper btUserLevelMapper;

    @Autowired
    private IBtUserAccountRecordService accountRecordService;

    @Autowired
    private IBtOrganizationRechargeRecordService organizationRechargeRecordService;

    @Autowired
    private BtOrganizationMapper organizationMapper;

    @Autowired
    private BtUserTicketMapper ticketMapper;


    /**
     * 查询用户
     * 
     * @param userId 用户ID
     * @return 用户
     */
    @Override
    public BtUser selectBtUserById(Integer userId)
    {
        return btUserMapper.selectBtUserById(userId);
    }

    @Override
    public BtUser selectBtUserByCard(String userCard,Integer userId) {
        return btUserMapper.selectBtUserByCard(userCard,userId);
    }

    /**
     * 查询用户
     *
     * @param idcardNum 身份证号
     * @return 用户
     */
    @Override
    public BtUser selectBtUserByIdcardNum(String idcardNum) {
        return btUserMapper.selectBtUserByIdcardNum(idcardNum);
    }

    @Override
    public BtUser selectBtUserByInvitationCode(String invitationCode, Integer userId) {
        return btUserMapper.selectBtUserByInvitationCode(invitationCode,userId);
    }

    @Override
    public BtUser selectBtUserByPhone(String phone) {
        return btUserMapper.selectBtUserByPhone(phone);
    }

    /**
     * 查询用户列表
     * 
     * @param btUser 用户
     * @return 用户
     */
    @Override
    public List<BtUser> selectBtUserList(BtUser btUser)
    {
        return btUserMapper.selectBtUserList(btUser);
    }

    @Override
    public List<BtUser> selectBtUserListByInvitationCode(BtUser btUser) {
        return btUserMapper.selectBtUserListByInvitationCode(btUser);
    }

    /**
     * 新增用户
     * 
     * @param btUser 用户
     * @return 结果
     */
    @Override
    public int insertBtUser(BtUser btUser)
    {
        btUser.setCreateTime(DateUtils.getNowDate());
        btUser.setInvitationCode(this.getCharAndNum(6));
        return btUserMapper.insertBtUser(btUser);
    }

    private String getCharAndNum(int num){
        String charAndNumr = SpringUtils.getCharAndNumr(num);
        BtUser btUser = btUserMapper.selectBtUserByInvitationCode(charAndNumr, null);
        if(!StringUtils.isNull(btUser)){
            charAndNumr = getCharAndNum(num);
        }
        return charAndNumr;
    }

    /**
     * 修改用户
     * 
     * @param btUser 用户
     * @return 结果
     */
    @Override
    public int updateBtUser(BtUser btUser)
    {
        btUser.setUpdateTime(DateUtils.getNowDate());
        return btUserMapper.updateBtUser(btUser);
    }

    /**
     * 充值 金豆
     * btBean 小于0是  为扣除  返还机构已充值金额  =  总充值金额 - 已扣除的总金额
     * @param btUser 用户
     * @return 结果
     */
    @Override
    public int recharge(BtUser btUser) throws Exception{
        Integer orgId = SecurityUtils.getLoginUser().getUser().getBtOrgId();
        BigDecimal btBean = btUser.getBtBean();//本次充值金额
        BigDecimal orgBtBean = btBean;//机构充值金额
        String type = "in";
        String orgType = "out";
        Integer actiontype = 8;
        Integer orgActiontype = 2;
        if(btBean.compareTo(BigDecimal.ZERO) == -1){  //btBean 小于0是  为扣除
            btBean = BigDecimal.ZERO.subtract(btBean);
            orgBtBean = btBean;
            BtUser btUserTemp = btUserMapper.selectBtUserById(btUser.getUserId());
            BigDecimal btBeanTemp = btUserTemp.getBtBean();
            if(btBeanTemp.compareTo(btBean) == -1){
                throw new CustomException("用户金豆不足！");
            }
            Integer rechargeSum = btUserMapper.selectBtBeanRechargeSumById(btUser.getUserId()); //用户被充值金额剩余
            BigDecimal bigRechargeSum = new BigDecimal(rechargeSum);
            if(bigRechargeSum.compareTo(orgBtBean) == -1){ //如果 被充值金额剩余 小于 本次扣除金额 则返还 机构 用户被充值金额剩余
                orgBtBean = bigRechargeSum;
            }
            type = "out";
            orgType = "in";
            actiontype = 18;
            orgActiontype = 4;
        }else{
            BtOrganization btOrganization = organizationMapper.selectBtOrganizationById(orgId);
            BigDecimal reBean = btOrganization.getReBean(); //充值金豆余额
            if(btBean.compareTo(reBean) == 1){
                throw new CustomException("账户余额不足，请联系平台充值！");
            }
        }
        if(orgBtBean.compareTo(BigDecimal.ZERO) == 1){
            organizationRechargeRecordService.updataOrgRecharge(orgId,btUser.getUserId(),orgBtBean,BigDecimal.ZERO,orgType,orgActiontype);
        }
        accountRecordService.updataUserAccount(btUser.getUserId(),btBean,BigDecimal.ZERO,null,null,type,actiontype);

        return 1;
    }

    /**
     * 充值 积分
     *
     * @param btUser 用户
     * @return 结果
     */
    @Override
    public int rechargeScore(BtUser btUser) {
        Integer orgId = SecurityUtils.getLoginUser().getUser().getBtOrgId();
        BigDecimal btScore = btUser.getBtScore();//本次充值金额
        String type = "in";
        Integer actiontype = 16;
        if(btScore.compareTo(BigDecimal.ZERO) == -1){
            btScore = BigDecimal.ZERO.subtract(btScore);
            BtUser btUserTemp = btUserMapper.selectBtUserById(btUser.getUserId());
            BigDecimal btScoreTemp = btUserTemp.getBtScore();
            if(btScoreTemp.compareTo(btScore) == -1){
                throw new RuntimeException("用户积分不足！");
            }
            type = "out";
            actiontype = 17;
        }
        try {
            accountRecordService.updataUserAccount(btUser.getUserId(),BigDecimal.ZERO,btScore,null,null,type,actiontype);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("操作失败");
        }
        return 1;
    }

    /**
     * 充值 奖券
     *
     * @param btUser 用户
     * @return 结果
     */
    @Override
    public int rechargeTicket(BtUser btUser) {
        Integer btTicket = btUser.getBtTicket();
        String username = SecurityUtils.getUsername();
        if(btTicket > 0){
            for (int i = 0; i < btTicket; i++) {
                //奖励奖券
                BtUserTicket btUserTicket = new BtUserTicket();
                btUserTicket.setUserId(btUser.getUserId());
                btUserTicket.setTotalFee(1500);
                btUserTicket.setCreateTime(DateUtils.getNowDate());
                btUserTicket.setCreateBy(username);
                ticketMapper.insertBtUserTicket(btUserTicket);
            }
        }
        return 1;
    }

    /**
     * 审核用户
     *
     * @param btUser 用户
     * @return 结果
     */
    @Override
    @Transactional
    public int checkBtUser(BtUser btUser)
    {
//        BtUser btUser1 = btUserMapper.selectBtUserById(btUser.getUserId());
//        BtUserLevel btUserLevel = btUserLevelMapper.selectBtUserLevelByLevel(btUser1.getUserLevel());
//        BigDecimal accountMoney = BigDecimal.valueOf(btUserLevel.getAccountMoney()); //发放金额
//        btUser.setBtBean(accountMoney);
        //审核通过增加余额  0205取消
//        if(1 == btUser.getStatus()){
//            try {
//                accountRecordService.updataUserAccount(btUser.getUserId(),accountMoney,BigDecimal.ZERO,null,null,"in",5);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        btUser.setUpdateTime(DateUtils.getNowDate());
        btUser.setUpdateBy(SecurityUtils.getUsername());
        return btUserMapper.updateBtUser(btUser);
    }

    /**
     * 批量删除用户
     * 
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteBtUserByIds(Integer[] userIds)
    {
        return btUserMapper.deleteBtUserByIds(userIds);
    }

    /**
     * 删除用户信息
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteBtUserById(Integer userId)
    {
        return btUserMapper.deleteBtUserById(userId);
    }

    /**
     * 查询用户 被充值金豆
     *
     * @param userId 用户ID
     * @return 用户
     */
    @Override
    public int selectBtBeanRechargeSumById(Integer userId) {
        return btUserMapper.selectBtBeanRechargeSumById(userId);
    }
}
